package com.tramy.cn.push.sender;

import com.tramy.cn.push.common.Data;
import com.tramy.cn.push.common.LEVEL;
import com.tramy.cn.push.common.PushRes;
import com.tramy.cn.push.common.XIAOMIInfo;
import com.xiaomi.xmpush.server.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.LinkedList;
import java.util.List;

public class XIAOMISender implements PushSender {

    public static final Log logger = LogFactory.getLog(XIAOMISender.class);

    private static final int RETRY_COUNT = 3;

    private final Sender sender;

    private final String pkgName;

    public XIAOMISender(XIAOMIInfo info) {
        Constants.useOfficial();
        sender = new Sender(info.getAppSecret());
        pkgName = info.getPackageName();
    }

    @Override
    public PushRes sendData(List<Data> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            logger.info("【CNPUSH SDK - XIAOMI】目标平台没有要进行的推送");
            return PushRes.ok();
        }

        List<TargetedMessage> targetedMessages = new LinkedList<>();
        for (Data data : dataList) {
            TargetedMessage targetedMessage = new TargetedMessage();
            targetedMessage.setTarget(TargetedMessage.TARGET_TYPE_REGID, data.getToken());
            targetedMessage.setMessage(getMessage(data));
            targetedMessages.add(targetedMessage);
        }

        try {
            Result result = sender.send(targetedMessages, RETRY_COUNT);
            return PushRes.build(
                    result.getErrorCode().getValue(),
                    result.getReason());
        }catch (Exception e) {
            e.printStackTrace();

            return PushRes.build(PushRes.ERROR, e.toString());
        }
    }

    private Message getMessage(Data data) {
        Message.Builder builder = new Message.Builder()
                .title(data.getTitle())
                .description(data.getContent())
                .restrictedPackageName(pkgName)
                .extra(Constants.EXTRA_PARAM_NOTIFY_EFFECT, Constants.NOTIFY_LAUNCHER_ACTIVITY);

        if (data.getGrantMi() && data.getLevel() == LEVEL.HIGH) {
            builder.extra("channel_id", "high_system");
        }

        return builder.build();
    }

}
